//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package persistence.utils;


public class GenericTokenParser {
    // 开始标记
    private final String openToken;
    // 结束标记
    private final String closeToken;
    // 标记处理器
    private final TokenHandler handler;

    public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
        this.openToken = openToken;
        this.closeToken = closeToken;
        this.handler = handler;
    }

    public String parse(String text) {
        if (text == null || text.isEmpty()) {
            return "";
        }
        int start = text.indexOf(this.openToken, 0);
        if (start == -1) {
            return text;
        }

        char[] src = text.toCharArray();
        int offset = 0;
        StringBuilder builder = new StringBuilder();

        for (StringBuilder expression = null; start > -1; start = text.indexOf(this.openToken, offset)) {
            if (start > 0 && src[start - 1] == '\\') {
                builder.append(src, offset, start - offset - 1).append(this.openToken);
                offset = start + this.openToken.length();
            } else {
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }

                builder.append(src, offset, start - offset);
                offset = start + this.openToken.length();

                int end;
                for (end = text.indexOf(this.closeToken, offset); end > -1; end = text.indexOf(this.closeToken, offset)) {
                    if (end <= offset || src[end - 1] != '\\') {
                        expression.append(src, offset, end - offset);
                        int var10000 = end + this.closeToken.length();
                        break;
                    }

                    expression.append(src, offset, end - offset - 1).append(this.closeToken);
                    offset = end + this.closeToken.length();
                }

                if (end == -1) {
                    builder.append(src, start, src.length - start);
                    offset = src.length;
                } else {
                    builder.append(this.handler.handleToken(expression.toString()));
                    offset = end + this.closeToken.length();
                }
            }
        }

        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }

        return builder.toString();

    }
}
